var validator 
var AppointmentAdd = function () {
	var handleValidation = function() {
            var formAdd = $('#addForm');
            jQuery.validator.addMethod("orderAmount", function(value, element) { 
            	return false;
    		}, "------");
            validator = formAdd.validate({
            	focusInvalid: false, // do not focus the last invalid input
                rules: {
                	name: {
                        required: true
                    },
                    product:{
                    	required: true
                    },
                    orderAmount:{
                        number: true,
                        remote: {
                            url: ctx + "/appointment/check",
                            type: "post",
                            dataType: "json",
                            data: {type : 1,
                            	productId : function(){
                           		return $('#productId').val();
                           	}}
                        }
                    },
                    appointTime:{
                    	required: true,
                        date: true
                    },
                    employeeNo:{
                    	required: true
                    }
                },
                messages: {
                	name: {required:"姓名不能为空！"},
                	product: {required:"意向产品不能为空！"},
                	orderAmount:{remote:"预约金额输入有误！"},
                	appointTime: {required:"预约时间不能为空！"},
                	employeeNo: {required:"理财师信息不能为空！"}
                },
                success: function (label, element) {
                    var icon = $(element).parent('.input-icon').children('i');
                    $(element).closest('.form-group').removeClass('has-error').addClass('has-success'); // set success class to the control group
                    icon.removeClass("fa-warning").addClass("fa-check");
                },

                submitHandler: function (form) {
                    var json = $('form#addForm').serializeJSON();
                    var invesId = $('#investorId').val();
                    var empId = $('#employeeId').val();
                    var prodId = $('#productId').val();
                    var orderAmount = parseFloat($('#orderAmount').val(),20);
                    var available = $('#available').val();
                    var subStart = $('#subStart').val();
                    if(invesId == ""){
                    	bootbox.alert("请输入投资人相关信息并选择投资人");
                    	return;
                    }
                    if(prodId == ""){
                    	bootbox.alert("请选择您的意向产品");
                    	return;
                    }
                    if(orderAmount != null && orderAmount != ''){
                    	if(orderAmount > available || orderAmount < subStart){
                    		bootbox.alert("预约金额输入有误!");
                        	return;
                    	}
                    }
                    if(empId == ""){
                    	bootbox.alert("请输入员工相关信息并选择员工");
                    	return;
                    }
                    var appointTime = $('#appointTime').val();
                    var a = (Date.parse(new Date()) - Date.parse(appointTime))/3600/1000;
                    if (a > 0) {
                    	bootbox.alert("预约时间填写错误！");
                    	return;
                    }
                    $.ajax({
                    	type:"post",
                        contentType:"application/json; charset=UTF-8",
                        url: ctx + "/appointment/doAdd",
                        data:json,
                        dataType:"json",
                        success: function(msg){
                        	if(msg.code == 0){
                        		showError(msg.message,2000,true);
                        		//bootbox.alert(msg.message);
                        		return;
                        	}
                        	$("#investorId").val('');
                            $("#investorName").val('');
                            $("#investorId").val('');
                            $("#investorName").val('');
                            $('#productId').val('');
                        	$('#productName').val('');
                        	$('#productBriefName').val('');
                        	$('#btn_reset').click();
                        	$('#start_amount').html('-');
                        	$('#end_amount').html('-');
                        	showTips(msg.message,2000,true);
                        },
                        error: function (msg) {
                        	showError('服务器偷了个小懒,新增预约失败了！',2000,true);
                        }
                    });
                }
            });
    }

    return {
        init: function () {
            handleValidation();
        }
    };
}();

$('#datetimepicker').datepicker(
		{
			autoclose:true
		}
);


//自动查询投资人
$("#myInvestor").autocomplete({
    source: function(query,process){
    	$.ajax({
        	type:"post",
            contentType:"application/json; charset=UTF-8",
            url: ctx + "/appointment/investor/"+query.term,
            dataType:"json",
            success: function(data){
            	$("#appo_submit").attr("disabled",false);
            	var ebean = [];
            	var length = data.length;
            	for (var int = 0; int < data.length; int++) {
            		var temp = [];
            		var name ,mobile,idCard,employeeId,employeeName,employeeNo;
            		if(data[int].name != null){
            			name = data[int].name ;
            		}else{
            			name = "--";
            		}
            		if(data[int].mobile != null){
            			mobile = data[int].mobile ;
            		}else{
            			mobile = "--";
            		}
            		if(data[int].idCard != null){
            			idCard = data[int].idCard ;
            		}else{
            			idCard = "--";
            		}
            		if(data[int].employeeId != null){
            			employeeId = data[int].employeeId ;
            		}else{
            			employeeId = "--";
            		}
            		if(data[int].employeeName != null){
            			employeeName = data[int].employeeName ;
            		}else{
            			employeeName = "--";
            		}
            		if(data[int].employeeNo != null){
            			employeeNo = data[int].employeeNo ;
            		}else{
            			employeeNo = "--";
            		}
            		temp.label = name +"  "+mobile+"  "+idCard;
            		temp.idcard = idCard;
            		temp.mobile = mobile;
            		temp.id = data[int].id;
            		temp.name = name;
            		temp.employeeId = employeeId;
            		temp.employeeName = employeeName;
            		temp.employeeNo = employeeNo;
            		ebean.push(temp);
        		}
                return process(ebean);
            }
        });
    },
    dataType:"json",
    max: 10, 
    search:function(event, ui){
    	$("#appo_submit").attr("disabled",false);
        $("#investorId").val('');
        $("#investorName").val('');
        $('#employeeNo').val('');
        $("#employeeName").html('');
        $("#employeeId").val('');
    },
    select: function(event, ui) {
        $("#myInvestor").val(ui.item.label);
        $("#investorName").val(ui.item.name);
        $("#investorId").val(ui.item.id);
        $('#employeeNo').val(ui.item.employeeName+"  "+ui.item.employeeNo);
        $("#employeeName").val(ui.item.employeeName);
        $("#employeeId").val(ui.item.employeeId);
        if(ui.item.employeeName == "--"){
        	$("#appo_submit").attr("disabled",true);
        	showError('该投资人还没有分配理财师,无法创建预约单！',2000,true);
        }
        // 阻止事件的默认行为
        event.preventDefault(); 
    }
});

/*//自动查询理财师
$("#employeeNo").autocomplete({
    source: function(query,process){
       $.post(ctx + "/investor/employee/"+query.term,{"matchCount":10},function(data){
        	var ebean = []
        	for (var int = 0; int < data.length; int++) {
        		var temp = [];
        		var employeeName ,employeeNo;
        		if(data[int].employeeName != null){
        			employeeName = data[int].employeeName ;
        		}else{
        			employeeName = "--";
        		}
        		if(data[int].employeeNo != null){
        			employeeNo = data[int].employeeNo ;
        		}else{
        			employeeNo = "--";
        		}
        		temp.label = employeeName +"  "+ employeeNo;
        		temp.no = employeeNo;
        		temp.id = data[int].employeeId;
        		temp.name = employeeName;
        		ebean.push(temp);
    		}
            return process(ebean);
        });
    },
    max: 10, 
    search:function(event, ui){
    	$("#employeeName").html('');
        $("#employeeNo").html('');
        $("#employeeId").val('');
    },
    select: function(event, ui) {
        $("#employeeName").val(ui.item.name);
        $("#employeeNo").val(ui.item.label);
        $("#employeeId").val(ui.item.id);
        var uistr =ui.item;
        // 阻止事件的默认行为
        event.preventDefault(); 
    }
});*/


function plu() {
	var se1 = $('#selGroupId')[0];
	var lenth = se1.length;
	var i=0;
	var num = 0;
	var flag = 0;
    for(;i<lenth;i++) {
        if(se1[i].selected) {
        	if(flag == 0 ){
        		num = i;
        	}
        	flag++;
        }
    }
    if(flag > 1 || flag == 0){
    	bootbox.alert("请选择一个意向产品!");
    	return;
    }else{
    	$('#product').val(se1[num].innerHTML);
    	$('#productId').val(se1[num].getAttribute('value'));
    	$('#productName').val(se1[num].getAttribute('productname'));
    	$('#productBriefName').val(se1[num].getAttribute('name'));
    	$('#available').val(se1[num].getAttribute('available'));
    	$('#subStart').val(se1[num].getAttribute('subStart'));
    	$("#orderAmount").val("");
    	validator.resetForm();
    	document.getElementById('start_amount').innerHTML = formatCurrency($('#subStart').val());
    	document.getElementById('end_amount').innerHTML= formatCurrency(new Number($('#available').val()));
    }
}

/** 
 * 将数值四舍五入(保留2位小数)后格式化成金额形式 
 * @param num 数值(Number或者String) 
 * @return 金额格式的字符串
 * @type String 
 */  
function formatCurrency(num) {  
    num = num.toString().replace(/\$|\,/g,'');  
    if(isNaN(num))  
        num = "0";  
    sign = (num == (num = Math.abs(num)));  
    num = Math.floor(num*100+0.50000000001);  
    cents = num%100;  
    num = Math.floor(num/100).toString();  
    if(cents<10)  
    cents = "0" + cents;  
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)  
    num = num.substring(0,num.length-(4*i+3))+','+  
    num.substring(num.length-(4*i+3));  
    return (((sign)?'':'-') + num + '.' + cents);  
}  

function change(){
	bootbox.alert("change");
}
function backList(){
	window.location.href = ctx +"/appointment/list";
}

//预约时间
function appoTimeChange(){
}